//
//  ViewController.m
//  iOS9Sample-Photos
//
//  Created by MJ Lee on 15/9/24.
//  Copyright © 2015年 小码哥（http://www.520it.com）. All rights reserved.
//

#import "ViewController.h"
#import <Photos/Photos.h>
#import "FBDPictureViewController.h"
#import <Social/Social.h>
#import "CallDirectoryHandler.h"
#import <CallKit/CallKit.h>
#import "FBDNavigaionViewController.h"
#import "FBDPhotoAlbumViewController.h"
#import "FBDPhotoBrowseViewController.h"
#import "UIImage+imageScale.h"
/** 相册名字 */
static NSString * const XMGCollectionName = @"冯哥-Photos";

@interface ViewController ()
{
    FBDPictureViewController* pictureVC;
    BOOL isStop;
    NSMutableArray *imageArr;//未压缩的图片
    NSMutableArray *imageArray;//经过压缩的图片
}

@property (nonatomic, strong) NSString *theVideoPath;

@property (nonatomic,strong)NSMutableArray* listPictureArray;
@property (nonatomic,strong)NSMutableArray* tempArray;

@end

@implementation ViewController
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
     
     
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    imageArray = [[NSMutableArray alloc] init];
    imageArr =[[NSMutableArray alloc]initWithObjects:
               [UIImage imageNamed:@"ren.png"],[UIImage imageNamed:@"未命名.png"],
               [UIImage imageNamed:@"ren.png"],[UIImage imageNamed:@"未命名.png"],
               [UIImage imageNamed:@"ren.png"],[UIImage imageNamed:@"未命名.png"],
               [UIImage imageNamed:@"ren.png"],[UIImage imageNamed:@"未命名.png"],
               [UIImage imageNamed:@"ren.png"],[UIImage imageNamed:@"未命名.png"],
               [UIImage imageNamed:@"ren.png"],[UIImage imageNamed:@"未命名.png"],nil];
    
    for (int i=0; i<10000; i++) {
        UIImage* indexImage=nil;
        if (i%2)
        {
            indexImage= [UIImage imageNamed:@"ren.png"];
        }else
        {
            indexImage= [UIImage imageNamed:@"ren.png"];
        }
        [imageArr addObject:indexImage];
        
    }
    
    
    
    
    
    for (int i = 0; i<imageArr.count; i++) {
        UIImage *imageNew = imageArr[i];
        //设置image的尺寸
        CGSize imagesize = imageNew.size;
        imagesize.height =408;
        imagesize.width =306;
        //对图片大小进行压缩--
//        imageNew = [imageNew scaleOriginImage:<#(UIImage *)#> scaleSize:<#(CGSize)#>:imageNew scaledToSize:imagesize];
        [imageArray addObject:imageNew];
    }
    
    self.listPictureArray=[NSMutableArray array];
    self.tempArray=[NSMutableArray array];
    
    NSUserDefaults *shareDefault=[[NSUserDefaults alloc]initWithSuiteName:@"group.com.MedSci"];
    [shareDefault setObject:@"我们" forKey:@"myName"];
    
    UIButton* twoButton=[[UIButton alloc] initWithFrame:CGRectMake(80, 200, 50, 30)];
    twoButton.backgroundColor=[UIColor greenColor];
    twoButton.titleLabel.font=[UIFont systemFontOfSize:10];
    [twoButton setTitle:@"打电话" forState:UIControlStateNormal];
    [twoButton addTarget:self action:@selector(telMyPhoneNumber) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:twoButton];
    
    CXCallDirectoryManager *manager = [CXCallDirectoryManager sharedInstance];
    // 获取权限状态
    [manager getEnabledStatusForExtensionWithIdentifier:@"cn.medsci.EDCsfzs.CallBack" completionHandler:^(CXCallDirectoryEnabledStatus enabledStatus, NSError * _Nullable error) {
        if (!error) {
            NSString *title = nil;
            if (enabledStatus == CXCallDirectoryEnabledStatusDisabled) {
                /*
                 CXCallDirectoryEnabledStatusUnknown = 0,
                 CXCallDirectoryEnabledStatusDisabled = 1,
                 CXCallDirectoryEnabledStatusEnabled = 2,
                 */
                title = @"未授权，请在设置->电话授权相关权限";
            }else if (enabledStatus == CXCallDirectoryEnabledStatusEnabled) {
                title = @"授权";
            }else if (enabledStatus == CXCallDirectoryEnabledStatusUnknown) {
                title = @"不知道";
            }
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                           message:title
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                                  handler:^(UIAlertAction * action) {}];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                           message:@"有错误"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                                  handler:^(UIAlertAction * action) {}];
            
//            [alert addAction:defaultAction];
//            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
    
    UIImage* indexImage=[UIImage imageNamed:@"ren"];
    int scaleNumber=3;
    
    indexImage=[indexImage scaleOriginImage:indexImage scaleSize:CGSizeMake(indexImage.size.width/scaleNumber,indexImage.size.height/scaleNumber)];
    UIImageView* fontImageView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 80,indexImage.size.width/scaleNumber,indexImage.size.height/scaleNumber)];
    fontImageView.backgroundColor=[UIColor greenColor];
    fontImageView.contentMode=UIViewContentModeScaleAspectFit;
    
    fontImageView.image=indexImage;
    
    
//    [self.view addSubview:fontImageView];
    
    
    
    
}
-(void)telMyPhoneNumber
{
//    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"tel://+8618017899902"]];
//    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms://itunes.apple.com/gb/app/yi-dong-cai-bian/id391945719?mt=8"]];
    
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    
    
    
}


/**
 * 获得自定义的相册对象
 */
- (PHAssetCollection *)collection
{
    // 先从已存在相册中找到自定义相册对象
    PHFetchResult<PHAssetCollection *> *collectionResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection *collection in collectionResult) {
        if ([collection.localizedTitle isEqualToString:XMGCollectionName]) {
            return collection;
        }
    }
    
    // 新建自定义相册
    __block NSString *collectionId = nil;
    NSError *error = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        collectionId = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:XMGCollectionName].placeholderForCreatedAssetCollection.localIdentifier;
    } error:&error];
    
    if (error) {
        NSLog(@"创建相册【%@】失败", XMGCollectionName);
        return nil;
    }
    
    
    
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[collectionId] options:nil].lastObject;
}

/**
 * 保存图片到相册
 */
- (IBAction)saveImage {
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusDenied) {
        NSLog(@"请到【设置-隐私-照片】打开访问开关");
    } else if (status == PHAuthorizationStatusRestricted) {
        NSLog(@"无法访问相册");
    } else {
        // 保存相片的标识
        __block NSString *assetId = nil;
        
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            // 保存相片到相机胶卷，并返回标识
            assetId = [PHAssetCreationRequest creationRequestForAssetFromImage:[UIImage imageNamed:@"logo"]].placeholderForCreatedAsset.localIdentifier;
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            if (!success) {
                NSLog(@"保存失败：%@", error);
                return;
            }
            
            // 根据标识获得相片对象
            PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetId] options:nil].lastObject;
            
            // 拿到自定义的相册对象
            PHAssetCollection *collection = [self collection];
            if (collection == nil) return;
            
            // 保存相片到自定义相册中
            [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                [[PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection] addAssets:@[asset]];
            } completionHandler:^(BOOL success, NSError * _Nullable error) {
                if (success) {
                    NSLog(@"保存成功");
                } else {
                    NSLog(@"保存失败：%@", error);
                }
            }];
        }];
    }
    

    
    
}

/**
 * 查询所有的图片
 */
- (IBAction)searchAllImages {
    

    
    [_listPictureArray removeAllObjects];
//    // 遍历所有的自定义相册
    dispatch_queue_t queue =dispatch_queue_create("come.fengbaodong.www", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        
        PHFetchResult<PHAssetCollection *> *collectionResult0 = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
        for (PHAssetCollection *collection in collectionResult0) {
            [self searchAllImagesInCollection:collection];
           
        }
        

        dispatch_sync(dispatch_get_main_queue(), ^{
        
        NSLog(@"_listPictureArray 的数量count：%ld",(unsigned long)_listPictureArray.count);
        //翻序
//        pictureVC.pictureListArray=[[_listPictureArray reverseObjectEnumerator] allObjects];;
//            pictureVC.pictureListArray=_listPictureArray;
//            [pictureVC reloadCollectionView];
            

            
        });
        
        
        
    });
    [self showFBDPictureViewController];
    
}

/**
 * 查询某个相册里面的所有图片
 */
- (void)searchAllImagesInCollection:(PHAssetCollection *)collection
{

    // 采取同步获取图片（只获得一次图片）
  
    NSLog(@"相册名字：%@", collection.localizedTitle);
    
    // 遍历这个相册中的所有图片
    PHFetchResult<PHAsset *> *assetResult = [PHAsset fetchAssetsInAssetCollection:collection options:nil];
    for (PHAsset *asset in assetResult) {
        // 过滤非图片
        if (asset.mediaType != PHAssetMediaTypeImage) continue;
        
        [_listPictureArray addObject:asset];
        
        
        
        
        
    }
}



-(void)showFBDPictureViewController
{
    
    
    
    pictureVC=[[FBDPhotoAlbumViewController alloc] init];
//    pictureVC.pictureListArray=_listPictureArray;
    pictureVC.view.backgroundColor=[UIColor whiteColor];
    
    FBDNavigaionViewController* photoNavVC=[[FBDNavigaionViewController alloc]initWithRootViewController:pictureVC];
    
    photoNavVC=[FBDNavigaionViewController sharePhotoesNavigaionVC];
    
    [self presentViewController:photoNavVC animated:YES completion:^{
        NSLog(@" present  进入了picktureViewController 视图控制器");
    }];
}






-(void)testCompressionSession
{
    //设置mov路径
    NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *moviePath =[[paths objectAtIndex:0]stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mov",@"test"]];
    self.theVideoPath=moviePath;
    
    //定义视频的大小320 480 倍数
    CGSize size =CGSizeMake(320,480);
    
    //        [selfwriteImages:imageArr ToMovieAtPath:moviePath withSize:sizeinDuration:4 byFPS:30];//第2中方法
    
    NSError *error =nil;
    //    转成UTF-8编码
    unlink([moviePath UTF8String]);
    NSLog(@"path->%@",moviePath);
    //     iphone提供了AVFoundation库来方便的操作多媒体设备，AVAssetWriter这个类可以方便的将图像和音频写成一个完整的视频文件
    AVAssetWriter *videoWriter = [[AVAssetWriter alloc] initWithURL:[NSURL fileURLWithPath:moviePath] fileType:AVFileTypeQuickTimeMovie error:&error];
    
    NSParameterAssert(videoWriter);
    if(error)
        NSLog(@"error =%@", [error localizedDescription]);
    //mov的格式设置 编码格式 宽度 高度
    NSDictionary *videoSettings =[NSDictionary dictionaryWithObjectsAndKeys:AVVideoCodecH264,AVVideoCodecKey,
                                  [NSNumber numberWithInt:size.width],AVVideoWidthKey,
                                  [NSNumber numberWithInt:size.height],AVVideoHeightKey,nil];
    
    AVAssetWriterInput *writerInput =[AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings];
    
    NSDictionary*sourcePixelBufferAttributesDictionary =[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:kCVPixelFormatType_32ARGB],kCVPixelBufferPixelFormatTypeKey,nil];
    //    AVAssetWriterInputPixelBufferAdaptor提供CVPixelBufferPool实例,
    //    可以使用分配像素缓冲区写入输出文件。使用提供的像素为缓冲池分配通常
    //    是更有效的比添加像素缓冲区分配使用一个单独的池
    AVAssetWriterInputPixelBufferAdaptor *adaptor =[AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:writerInput sourcePixelBufferAttributes:sourcePixelBufferAttributesDictionary];
    
    NSParameterAssert(writerInput);
    NSParameterAssert([videoWriter canAddInput:writerInput]);
    
    if ([videoWriter canAddInput:writerInput])
    {
        NSLog(@"11111");
    }
    else
    {
        NSLog(@"22222");
    }
    
    [videoWriter addInput:writerInput];
    
    [videoWriter startWriting];
    [videoWriter startSessionAtSourceTime:kCMTimeZero];
    
    //合成多张图片为一个视频文件
    dispatch_queue_t dispatchQueue =dispatch_queue_create("mediaInputQueue",NULL);
    int __block frame =0;
    [writerInput requestMediaDataWhenReadyOnQueue:dispatchQueue usingBlock:^{
        
        while([writerInput isReadyForMoreMediaData])
        {
            if(++frame >=[imageArray count]*10)
            {
                [writerInput markAsFinished];
                [videoWriter finishWritingWithCompletionHandler:^{
                    NSLog(@"完成了写入。。。。。。。。。。。。。。。。。。。。");
                }];
                //              [videoWriterfinishWritingWithCompletionHandler:nil];
                break;
            }
            CVPixelBufferRef buffer =NULL;
            int idx =frame/10;
            NSLog(@"idx==%d",idx);
            buffer = (CVPixelBufferRef)[self pixelBufferFromCGImage:[[imageArray objectAtIndex:idx] CGImage] size:size];
            
            if (buffer)
            {
                if(![adaptor appendPixelBuffer:buffer withPresentationTime:CMTimeMake(frame,30)])//设置每秒钟播放图片的个数
                {
                    NSLog(@"FAIL");
                }
                else
                {
                    NSLog(@"OK");
                }
                
                CFRelease(buffer);
            }
        }
    }];
    
}

- (CVPixelBufferRef)pixelBufferFromCGImage:(CGImageRef)image size:(CGSize)size
{
    NSDictionary *options =[NSDictionary dictionaryWithObjectsAndKeys:
                            [NSNumber numberWithBool:YES],kCVPixelBufferCGImageCompatibilityKey,
                            [NSNumber numberWithBool:YES],kCVPixelBufferCGBitmapContextCompatibilityKey,nil];
    CVPixelBufferRef pxbuffer =NULL;
    CVReturn status =CVPixelBufferCreate(kCFAllocatorDefault,size.width,size.height,kCVPixelFormatType_32ARGB,(__bridge CFDictionaryRef) options,&pxbuffer);
    
    NSParameterAssert(status ==kCVReturnSuccess && pxbuffer !=NULL);
    
    CVPixelBufferLockBaseAddress(pxbuffer,0);
    
    void *pxdata =CVPixelBufferGetBaseAddress(pxbuffer);
    NSParameterAssert(pxdata !=NULL);
    CGColorSpaceRef rgbColorSpace=CGColorSpaceCreateDeviceRGB();
    //    当你调用这个函数的时候，Quartz创建一个位图绘制环境，也就是位图上下文。当你向上下文中绘制信息时，Quartz把你要绘制的信息作为位图数据绘制到指定的内存块。一个新的位图上下文的像素格式由三个参数决定：每个组件的位数，颜色空间，alpha选项
    CGContextRef context =CGBitmapContextCreate(pxdata,size.width,size.height,8,4*size.width,rgbColorSpace,kCGImageAlphaPremultipliedFirst);
    NSParameterAssert(context);
    
    //使用CGContextDrawImage绘制图片  这里设置不正确的话 会导致视频颠倒
    //    当通过CGContextDrawImage绘制图片到一个context中时，如果传入的是UIImage的CGImageRef，因为UIKit和CG坐标系y轴相反，所以图片绘制将会上下颠倒
    CGContextDrawImage(context,CGRectMake(0,0,CGImageGetWidth(image),CGImageGetHeight(image)), image);
    // 释放色彩空间
    CGColorSpaceRelease(rgbColorSpace);
    // 释放context
    CGContextRelease(context);
    // 解锁pixel buffer
    CVPixelBufferUnlockBaseAddress(pxbuffer,0);
    
    return pxbuffer;
}

//播放
-(void)playAction
{
    NSLog(@"************%@",self.theVideoPath);
    NSURL *sourceMovieURL = [NSURL fileURLWithPath:self.theVideoPath];
    AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:sourceMovieURL options:nil];
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
    AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
    playerLayer.frame = self.view.layer.bounds;
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    [self.view.layer addSublayer:playerLayer];
    [player play];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
    NSLog(@"didReceiveMemoryWarningFrom ViewController");
    
}



@end
